from django.http import Http404, HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.core.urlresolvers import reverse
from django.contrib.admin.views.decorators import staff_member_required

from s_te.utils import delete_slug
from bl_rb.models import Blurb
from bl_rb.admin.forms import BlurbForm

@staff_member_required
def main(request, template_name="bl_rb/admin/main.html"):
    """
    The main page of the admin, listing all blurbs
    """
    blurbs = Blurb.objects.all()
    return render_to_response(template_name, {'blurbs':blurbs, 'nav_page': 'bl_rb_admin_main'},
                              context_instance=RequestContext(request))
    
@staff_member_required
def create(request, template_name="bl_rb/admin/create.html"):
    """
    Create a new blurb
    """
    if request.POST:
        form = BlurbForm(request.POST)
        if form.is_valid():
            form.save()
            request.user.message_set.create(message="Blurb created.")
            return HttpResponseRedirect(reverse('bl_rb_admin_main'))
    else:
        form = BlurbForm()
    return render_to_response(template_name, {'form':form},
                              context_instance=RequestContext(request))
    
@staff_member_required
def edit(request, slug, template_name="bl_rb/admin/edit.html"):
    """
    Edit an existing blurb
    """
    blurb = get_object_or_404(Blurb, slug=slug)
    if request.POST:
        form = BlurbForm(request.POST, instance=blurb)
        if form.is_valid():
            form.save()
            request.user.message_set.create(message="Blurb saved.")
            return HttpResponseRedirect(reverse('bl_rb_admin_main'))
    else:
        form = BlurbForm(instance=blurb)
    return render_to_response(template_name, {'blurb':blurb, 'form':form},
                              context_instance=RequestContext(request))

@staff_member_required
def delete(request):
    """
    Delete an existing blurb
    """
    delete_slug(Blurb, request)
    request.user.message_set.create(message="Blurb deleted.")
    return HttpResponseRedirect(reverse('bl_rb_admin_main'))
